I've written a simple substitution cipher using a dictionary for the keys/values containing letters, numbers, and some symbols. I could not, however, find a way to implement a key/value for "enter" (newline). Is there a way I could make it work as a dictionary value or would it require me to re-write the code in a different way?
Also, in a completely different question, is it possible to create a dictionary in JS using regex instead of inserting a unique key-value for each entry? What would that look like?
Here's how I've done it:
//Substitution function
let caseString = message.value.toUpperCase().split("");
let newString = [];
for (let unit of caseString) {
for (let letter in alphabet) {
if (unit === alphabet[letter]) {
newString.push(alphabet[unit]);
}
}
}
cipher.value = newString.join("");
//Dictionary object holding the alphabet keys & values
const alphabet = {
A: "Z",
B: "Y",
C: "X",
D: "W",
E: "V",
F: "U",
G: "T",
H: "S",
I: "R",
J: "Q",
K: "P",
L: "O",
M: "N",
N: "M",
O: "L",
P: "K",
Q: "J",
R: "I",
S: "H",
T: "G",
U: "F",
V: "E",
W: "D",
X: "C",
Y: "B",
Z: "A",
" ": " ",
"-": "-",
_: "_",
"!": "!",
":": ":",
";": ";",
"'": "'",
'"': '"',
$: "$",
"%": "%",
"&": "&",
"*": "*",
"(": "(",
")": ")",
"@": "@",
1: "1",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
9: "9",
0: "0",
};
I'm aware it might be a silly approach to it, but I wanted to practice and see if I could actually make it work. Thanks in advance!
The newline character is represented with "\n" so you could add it to your dictonary like this:
{
"\n": "\n"
}
As for dictonaries with regex, you can try passing a replacement function to a string's .replace() funktion. For example, this would change out only letters:
const input = "hello! 123"
const replace = {
A: "f",
B: "a",
// ...
h: "U",
e: "T",
l: "A",
o: "k",
}
const result = input.replace(
/[A-z]/g,
letter => replace[letter]
)
console.log(result) // <- "UTAAk! 123"
If you want to simplify your algorithm, check out the charCodeAt() and fromCharCode() functions.